<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-bgc">
        <img src="../assets/image/logo.jpg" alt="" />
        <span class="title">韶关废品智慧回收平台</span>
      </div>

      <van-tabs v-model:active="active">
        <van-tab title="手机号登录">
          <!-- 手机号登录表单 -->
          <div class="phone-form">
            <van-form ref="PhoneRef">
              <van-cell-group inset>
                <van-field
                  v-model="phoneForm.phone"
                  name="phone"
                  label="手机号码"
                  placeholder="请输入手机号码"
                  :rules="phoneFormRules.phone"
                  autocomplete="off"
                />
                <van-field
                  v-model="phoneForm.code"
                  center
                  clearable
                  label="短信验证码"
                  placeholder="短信验证码"
                >
                  <template #button>
                    <van-button size="small" type="primary" @click="getPhoneCode"
                      >发送验证码</van-button
                    >
                  </template>
                </van-field>
              </van-cell-group>
              <!-- 提交按钮 -->
              <div class="login-btns">
                <van-button round block type="primary" native-type="submit" @click="onPhoneLogin">
                  登录
                </van-button>
              </div>
            </van-form>
          </div>
        </van-tab>
        <van-tab title="密码登录">
          <!-- 密码登录表单 -->
          <div class="pwd-form">
            <van-form ref="loginRef">
              <van-cell-group inset>
                <van-field
                  v-model="loginForm.username"
                  name="username"
                  label="用户名"
                  placeholder="请输入用户名"
                  :rules="loginFormRules.username"
                  autocomplete="off"
                />
                <van-field
                  v-model="loginForm.password"
                  name="password"
                  type="password"
                  label="密码"
                  placeholder="请输入密码"
                  :rules="loginFormRules.password"
                />
                <van-field
                  v-model="sendcheckcode"
                  name="checkcode"
                  label="验证码"
                  class="checkcode"
                  placeholder="验证码"
                  :rules="loginFormRules.checkcode"
                  autocomplete="off"
                >
                  <template #button>
                    <!-- 验证码图片 -->
                    <div class="checkcode-pic">
                      <img :src="checkcode.aliasing" alt="" />
                    </div>
                  </template>
                </van-field>
              </van-cell-group>
              <!-- 提交按钮 -->
              <div class="login-btns">
                <van-button round block type="primary" @click="onRegister"> 注册 </van-button>
                <van-button round block type="primary" native-type="submit" @click="onLogin">
                  登录
                </van-button>
              </div>
              <p class="forget-pwd" @click="onforgetPwd">忘记密码？</p>
            </van-form>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import { showToast } from 'vant'
import { getCheckPic, reCheckPic, userLogin, getPhoneCode } from '../api/user.js'
export default {
  data() {
    return {
      active: 0,
      loginForm: {
        username: '',
        password: ''
      },
      // 登录表单的验证规则
      loginFormRules: {
        username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
        checkcode: [{ required: true, message: '请填写验证码', trigger: 'blur' }]
      },
      // 服务器传送过来的验证码
      checkcode: {
        key: '',
        aliasing: ''
      },
      // 用户端输入的登录验证码
      sendcheckcode: '',
      // 手机登录表单
      phoneForm: {
        phone: '',
        code: ''
      },
      // 手机登录表单的验证规则
      phoneFormRules: {
        phone: [
          { required: true, message: '请填写手机号码', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！', trigger: 'blur' }
        ],
        code: [{ required: true, message: '请填写验证码', trigger: 'blur' }]
      },
      // 发送过来的手机验证码
      phoneCode: ''
    }
  },
  created() {
    // 获取密码登录验证码
    this.getCheckCode()
  },
  methods: {
    // 获取密码登录验证码
    async getCheckCode() {
      const { data: res } = await getCheckPic()
      this.checkcode = res
    },
    // 密码登录按钮
    async onLogin() {
      // 1. 验证表单项
      this.$refs.loginRef
        .validate()
        .then(async () => {
          // 2. 验证验证码是否正确
          const params = { key: this.checkcode.key, code: this.sendcheckcode }
          const res1 = await reCheckPic(params)
          // if 验证码正确
          if (res1.data) {
            // 3. 提交表单数据
            const loginInfo = {
              client_id: 'sgWasteApp',
              client_secret: 'sgWasteApp',
              grant_type: 'password',
              username: JSON.stringify({
                username: this.loginForm.username,
                authType: 'password',
                password: this.loginForm.password
              })
            }
            const { data: res2 } = await userLogin(loginInfo)
            // 登录成功
            if (!res2.error) {
              // 4. 存储token
              window.sessionStorage.setItem('token', res2.access_token)
              this.$router.push('/home')
            } else {
              return showToast(res2.error_description)
            }
          } else {
            this.sendcheckcode = ''
            return showToast('验证码错误')
          }
        })
        .catch(() => {
          return showToast('信息填写有误')
        })
    },
    // 忘记密码
    onforgetPwd() {
      console.log('111')
      this.$router.push('/phonecode')
    },
    // 获取手机验证码
    async getPhoneCode() {
      if (this.phoneForm.phone) {
        const phoneMsg = { phone: this.phoneForm.phone }
        const { data: res } = await getPhoneCode(phoneMsg)
        if (res !== '发送成功') {
          return showToast('验证码获取失败')
        }
      } else {
        return showToast('请先输入手机号码')
      }
    },
    // 手机登录按钮
    onPhoneLogin() {
      this.$refs.PhoneRef.validate()
        .then(async () => {
            const PhoneInfo = {
              client_id: 'sgWasteApp',
              client_secret: 'sgWasteApp',
              grant_type: 'password',
              username: JSON.stringify({
                cellphone: this.phoneForm.phone,
                authType: 'ssm',
                password: this.phoneForm.code
              })
            }
          const { data: res } = await userLogin(PhoneInfo)
          window.sessionStorage.setItem('token', res.access_token)
          this.$router.push('/home')
        })
        .catch(() => {
          return showToast('信息填写有误')
        })
    },
    // 注册
    onRegister() {
      this.$router.push('/register')
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  position: fixed;
  left: 0;
  top: 0;
  height: 100%;
  background-color: #f3f3f3;

  .login-box {
    // 背景
    .login-bgc {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 256px;
      margin-top: -10px;
      background-color: #a8ebab;

      img {
        width: 90px;
        height: 90px;
        border-radius: 50%;
        background-color: #fff;
      }

      .title {
        font: normal 600 24px serif;
        margin-top: 20px;
      }
    }

    // 密码登录表单
    .pwd-form {
      display: flex;
      justify-content: center;
      margin: 0 auto;
      width: 98%;
      margin-top: 5px;
      padding-top: 20px;
      box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.1);
      border-radius: 3px;

      .van-form {
        margin-top: 10px;
        .van-cell-group {
          margin: 0 20px;
          background-color: #f3f3f3;

          .van-field {
            align-items: center;
            height: 58px;

            margin: 10px 0;
            border: 1px solid #a8ebab;
            border-radius: 3px;
            font-size: 18px;
          }
        }

        .login-btns {
          display: flex;
          justify-content: space-around;
          margin: 30px 0;

          .van-button {
            width: 40%;
            font-size: 18px;
          }
        }

        .forget-pwd {
          margin-right: 20px;
          color: #1989fa;
          text-align: right;
        }
      }
    }

    // 手机号码登录表单
    .phone-form {
      display: flex;
      justify-content: center;
      margin: 0 auto;
      width: 98%;
      margin-top: 5px;
      padding-top: 20px;
      box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.1);
      border-radius: 3px;

      .van-form {
        margin-top: 10px;
        .van-cell-group {
          margin: 0 20px;
          background-color: #f3f3f3;

          .van-field {
            align-items: center;
            height: 58px;

            margin: 10px 0;
            border: 1px solid #a8ebab;
            border-radius: 3px;
            font-size: 18px;
          }
        }

        .login-btns {
          display: flex;
          justify-content: center;
          margin: 30px 0;

          .van-button {
            width: 40%;
            font-size: 18px;
          }
        }
      }
    }
  }

  // 验证码
  .van-field:nth-child(3) {
    position: relative;
    margin: 0;
    padding: 0 0;
    padding-left: 16px;
  }

  .checkcode-pic {
    position: absolute;
    right: 0;
    top: -18px;
    background-color: skyblue;
    width: 50%;
    height: 58px;
    line-height: 58px;
    text-align: center;

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
